package com.speedchina.framework.base;

import com.speedchina.framework.utils.JSONUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 基础查询参数模型,支持分页参数、实体类和map无限扩展
 *
 * @author hank
 * @create 2018-10-19 上午10:41
 **/

public class QueryModel<M> extends LinkedHashMap<String,Object> {

    private int page;
    private int limit;
    private M m;

    public QueryModel(){
        init(1, 15, null);
    }

    public QueryModel(Integer page, Integer limit, M params){
        init(page, limit, params);
    }

    /**
     * 构造函数
     * @param params 该参数只有与 T 属性相同的才会被转换,该函数适用于controller层使用
     */
    public QueryModel(Map<String,Object> params, Class<M> clazz){
        if(params == null){ params = new HashMap<String,Object>(); }
        M m = JSONUtils.parse(JSONUtils.toJSONString(params), clazz);
        Integer page = null,limit = null;
        if(params.containsKey("page")){ page = Integer.valueOf(params.get("page").toString()); }
        if(params.containsKey("limit")){ limit = Integer.valueOf(params.get("limit").toString()); }
        init(page, limit, m);
    }

    public void init(Integer page, Integer limit,M param){ // param 非空约束
        if(page == null || page < 0){ page = 1; }
        if(limit == null || limit < 0){ limit = 15; }
        this.page = page;
        this.limit = limit;
        this.m = param;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public M getM() {
        return m;
    }
}
